package com.loong.game2048.controller;

import com.loong.game2048.Exception.BizException;
import com.loong.game2048.Exception.BizExceptionCodeEnum;
import com.loong.game2048.annotation.Authorize;
import com.loong.game2048.module.*;
import com.loong.game2048.module.vo.*;
import com.loong.game2048.server.CommentServer;
import com.loong.game2048.server.ForumServer;
import com.loong.game2048.server.PictureServer;
import com.loong.game2048.util.FileUtils;
import com.loong.game2048.util.ResultUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.loong.game2048.module.vo.Result;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
public class ForumController {

    @Value("${web.upload-path}")
    private String path;

    @Value("${web.url}")
    private String url;

    @Autowired
    private ForumServer forumServer;
    @Autowired
    private CommentServer commentServer;
    @Autowired
    private PictureServer pictureServer;

    @Authorize
    @GetMapping("/editForum/{id}")
    public Result edit(HttpServletRequest request,@PathVariable("id") Integer id){
        //获取用户ID
        String openId = ResultUtils.getOpenId(request);
        Forum forum = forumServer.findById(id);

        if (openId.equals(forum.getUid())){
            ForumVo forumVo = new ForumVo();
            BeanUtils.copyProperties(forum,forumVo);
            //查找帖子图片
            List<String> pictures = pictureServer.findByFidOnlyName(id);
            forumVo.setPictures(pictures);
            Result<ForumVo> result = new Result<>();
            result.setCode(ResultCode.SUCCESS);
            result.setData(forumVo);
            return result;
            //return forumVo;
        }else {
            //无权编辑
            throw new BizException(BizExceptionCodeEnum.NO_EDIT_PERMISSION);
        }

    }

    @Authorize
    @PostMapping("/editForum/{id}")
    public Result doEdit(Forum forum,
                          HttpServletRequest request,
                          @PathVariable("id") Integer id,
                          String[] pictures){
        //获取用户ID
        String openId = ResultUtils.getOpenId(request);
        if (openId.equals(forum.getUid())){

            //原图片集合
            Set<String> dbPicNames = new HashSet<String>();
            //新图片集合
            List<String> newPicNames = new ArrayList<>();

            //查找帖子原图片
            List<Picture> dbPictures = pictureServer.findByFid(id);
            for (Picture dbPicture : dbPictures) {
                dbPicNames.add(dbPicture.getP_name());
            }

            //新照片集合与旧照片集合比较
            for (String picture : pictures) {
                if (dbPicNames.contains(picture)){
                    dbPicNames.remove(picture);
                }else {
                    newPicNames.add(picture);
                }
            }

            //删除旧图片
            for (String dbPicName : dbPicNames) {
                //删除硬盘文件
                FileUtils.deleteFile(path+"/"+dbPicName);
                //删除数据库记录
                pictureServer.deleteByNameAndFid(dbPicName,id);
            }

            //更新帖子
            forumServer.update(forum);

            //更新图片
            pictureServer.addPictures(newPicNames,id);

            Result result = new Result();
            result.setCode(ResultCode.SUCCESS);
            result.setMsg("编辑成功");
            return result;
        }else {
            //无权编辑帖子
            throw new BizException(BizExceptionCodeEnum.NO_EDIT_PERMISSION);
        }

    }



    /**
     *
     * @param forum:帖子内容
     * @param request：
     * @param pictures：上传的图片名称
     * @return
     */
    @Authorize
    @PostMapping("/pubForum")
    public Result publish(Forum forum,
                          HttpServletRequest request,
                          @RequestParam(value = "pictures",required = false) String[] pictures) {

        //验证帖子完整性
        if (forum.getTag() == null || forum.getContent() == null || forum.getTitle() == null){
            Result result = new Result();
            result.setCode(ResultCode.PARAMETER_ERROR);
            result.setMsg("帖子的标题、内容、标签均不可为空！");
            return result;
        }

        //获取用户ID
        String openId = ResultUtils.getOpenId(request);
        forum.setUid(openId);

        //插入数据库
        forumServer.addForum(forum);
        Result result = new Result();


        //录入照片
        if (pictures == null || pictures.length == 0){
        }else {
            for (String pName : pictures) {
                //写入数据库
                Picture picture = new Picture();
                picture.setF_id(forum.getId());
                picture.setP_name(pName);
                pictureServer.addPicture(picture);
            }

        }
        result.setCode(ResultCode.SUCCESS);
        result.setMsg("发帖成功");
        return result;
    }


    @Authorize
    @GetMapping("/delForum/{id}")
    public Result delete(HttpServletRequest request,
                         @PathVariable("id") Integer id){

        //获取用户ID
        String openId = ResultUtils.getOpenId(request);
        Forum forum = forumServer.findById(id);
        //删帖
        if (openId.equals(forum.getUid())){

            //删除硬件的图片
            List<Picture> pictures = pictureServer.findByFid(id);
            for (Picture picture : pictures) {
                String dbPicName = picture.getP_name();
                //删除硬盘文件
                FileUtils.deleteFile(path+"/"+dbPicName);
            }

            //删除帖子
            forumServer.delForum(id);

            //删除帖子图片
            pictureServer.deleteByFid(id);

            Result result = new Result();
            result.setMsg("删除成功");
            result.setCode(ResultCode.SUCCESS);
            return result;
        }else {
            //删帖失败
            throw new BizException(BizExceptionCodeEnum.NO_DEL_PERMISSION);
        }
    }



    /**
     * 查看帖子详情
     * @param id:帖子的id
     * @return
     */
    @ResponseBody
    @GetMapping("/forum/{id}")
    public Result forum(@PathVariable("id") Integer id){
        //查找帖子
        Forum forum = forumServer.findById(id);
        if (forum == null){
            throw new BizException(BizExceptionCodeEnum.NO_SUCH_FORUM);
        }

        ForumDetailVo forumDetailVo = new ForumDetailVo();
        BeanUtils.copyProperties(forum,forumDetailVo);

        List<String> pictures = pictureServer.findByFidOnlyName(id);
        forumDetailVo.setPictures(pictures);

        //一级评论
        List<CommentVo> commentVos = commentServer.findByParentId(id);
        if (commentVos == null || commentVos.size() == 0){
            Result<ForumDetailVo> result = new Result<>();
            result.setCode(200);
            result.setData(forumDetailVo);
            //return forumDetailVo;
            return result;
        }

        forumDetailVo.setCommentVos(commentVos);

        //二级评论
        for (CommentVo commentVo : forumDetailVo.getCommentVos()) {
            List<CommentVo> commentVo2s = commentServer.findByParentId(commentVo.getId());
            commentVo.setCommentVo2s(commentVo2s);
        }

        Result<ForumDetailVo> result = new Result<>();
        result.setCode(ResultCode.SUCCESS);
        result.setData(forumDetailVo);
        //return forumDetailVo;
        return result;
    }


    /**
     * 论坛首页
     * @param page：第几页
     * @param size：每页显示几条
     * @param tag：帖子分类
     * @return
     */
    @ResponseBody
    @GetMapping("/forum")
    public Result allforum( @RequestParam(name = "page",defaultValue = "1",required = false) Integer page,
                            @RequestParam(name = "size",defaultValue = "5",required = false) Integer size,
                            @RequestParam(name = "tag",required = false)      Integer tag){
        PaginationVo paginationVo = forumServer.list(page,size,tag);

        Result<PaginationVo> result = new Result<>();
        result.setCode(ResultCode.SUCCESS);
        result.setData(paginationVo);
        //return paginationVo;
        return result;
    }




}
